<template>
  <div class="cusbtn">
    <div class="table-title">
      <!-- {{ $srv.getI18nByPath('piece.oQueryLinkSettingc.custombutton') }} -->
      <Icon
        class="custom-btn-add"
        type="ios-add-circle"
        @click="addCustomBtn"
      />

      <Icon
        class="custom-btn-remove"
        type="ios-remove-circle"
        @click="removeCustomBtn"
      />
    </div>

    <div class="custom-btn-content" v-if="config">
      <div
        v-for="(item, idx) of config"
        :key="idx"
        class="custom-btn-container"
        :id="'custom-btn-' + idx"
      >
        <div @contextmenu.prevent="customBtnRChecked($event, item, idx)">
          <Dropdown>
            <Button
              type="default"
              @click="customBtnChecked($event, item, idx)"
              :class="{ checked: item.checked }"
              :custom-icon="'wy-icon ' + item.icon"
            >
              {{ $srv.getI18nBySrv(item.title) }}
              <Icon
                type="ios-arrow-down"
                v-if="item.children.length > 0"
              ></Icon>
            </Button>
            <DropdownMenu v-if="item.children.length > 0" slot="list">
              <DropdownItem v-for="(itm, index) of item.children" :key="index">
                {{ $srv.getI18nBySrv(itm.title) }}
              </DropdownItem>
            </DropdownMenu>
          </Dropdown>
        </div>
      </div>
    </div>

    <div class="custom-btn-attrset" :style="G_attrSize" v-if="showAttrSet">
      <div>
        {{
          $srv.getI18nByPath('oSetupPanel.SetupAttrLibfield.detailedsettings')
        }}
      </div>
      <o-i18n-selector
        class="custom-btn-title"
        v-model="custBtnAttr.selTitle"
        @on-dochange="saveDetailToConfig"
        :placeholder="$srv.getI18nByPath('piece.oQueryLinkSettingc.buttonname')"
      >
      </o-i18n-selector>

      <o-combobox
        :compBoxInfo="GT_compBoxInfo"
        :config="comboBoxConf"
        @on-change="onIconChange"
      />

      <o-m2o-selector
        :clearable="true"
        v-model="custBtnAttr.m2oSel"
        :placeholder="$srv.getI18nByPath('piece.oRulesSetting.rule')"
        @on-dochange="saveDetailToConfig"
        :tTable="$srv.globalVar.tableName.PUB_API"
        :tField="$srv.globalVar.fieldName.pubApiName"
      ></o-m2o-selector>
      <Row class-name="custom-btn-checkbox-left">
        <Col span="12"
          ><Checkbox
            v-model="custBtnAttr.initDisabled"
            @on-change="saveDetailToConfig"
            >{{ $srv.getI18nByValue('初始不可用') }}</Checkbox
          ></Col
        >
        <Col span="12"
          ><Checkbox
            v-model="custBtnAttr.chkEnabled"
            @on-change="saveDetailToConfig"
            >{{ $srv.getI18nByValue('勾选可用') }}</Checkbox
          ></Col
        >
      </Row>
      <Row class-name="custom-btn-checkbox-left">
        <Col span="12"
          ><Checkbox
            v-model="custBtnAttr.initNotshow"
            @on-change="saveDetailToConfig"
            >{{ $srv.getI18nByValue('初始不显示') }}</Checkbox
          ></Col
        >
        <Col span="12"
          ><Checkbox
            v-model="custBtnAttr.chkShow"
            @on-change="saveDetailToConfig"
            >{{ $srv.getI18nByValue('勾选显示') }}</Checkbox
          ></Col
        >
      </Row>
      <Row class-name="custom-btn-checkbox-left">
        <Col span="12"
          ><Checkbox
            v-model="custBtnAttr.singleSelChk"
            @on-change="saveDetailToConfig"
            >{{ $srv.getI18nByValue('单选触发检查') }}</Checkbox
          ></Col
        >
        <Col span="12"
          ><Checkbox
            v-model="custBtnAttr.readCurrentStatus"
            @on-change="saveDetailToConfig"
            >{{ $srv.getI18nByValue('读取当前状态') }}</Checkbox
          ></Col
        >
      </Row>
      <Row class-name="custom-btn-checkbox-left">
        <Col span="12"
          ><Checkbox
            v-model="custBtnAttr.editedShow"
            @on-change="saveDetailToConfig"
            >{{ $srv.getI18nByValue('编辑时显示') }}</Checkbox
          ></Col
        >
        <Col span="12"
          ><Checkbox
            v-model="custBtnAttr.editedEnabled"
            @on-change="saveDetailToConfig"
            >{{ $srv.getI18nByValue('编辑时可用') }}</Checkbox
          ></Col
        >
      </Row>
      <Divider />
      <ButtonGroup sytle="float:right">
        <Button
          class="float: right"
          type="primary"
          size="small"
          @click="custBtnAttrsetClick"
          >{{ $srv.getI18nByPath('others.ok') }}</Button
        >
      </ButtonGroup>
    </div>
  </div>
</template>

<script lang="ts">
import { T_srv, Tsrv, ifs, ts, vue } from '@/services';

@T_srv.comp
export default class oCustomBtnSetting extends vue {
  @T_srv.model('modelchange') config: Array<any>;
  // @T_srv.prop({
  //   required: true,
  //   type: Array,
  //   default: []
  // })
  // value: Array<any>;

  /* 父组件compBoxInfo */
  @T_srv.prop({
    required: false,
    type: Object,
    default: null
  })
  compBoxInfo: ifs.I_compBoxInfo;

  /* 组件名 */
  private G_compName: string = 'oCustomBtnSetting';

  /* 组件箱信息对象 */
  private GT_compBoxInfo: ifs.I_compBoxInfo;

  /* 组件箱对象 */
  private GT_compBox: ifs.I_compBox;

  /* 组件箱识别ID */
  private G_compID: string;

  private currChkBtnIdx: number = -1;

  private showAttrSet: boolean = false;

  private G_attrSize: any = { top: '0px', left: '0px' };

  // private config: Array<any> = [];

  private custBtnAttr = {
    selTitle: '',
    m2oIcon: '',
    m2oSel: '',
    initDisabled: false,
    chkEnabled: false,
    initNotshow: false,
    chkShow: false,
    singleSelChk: false,
    readCurrentStatus: false,
    editedShow: false,
    editedEnabled: false
  };

  private comboBoxConf: any = {
    i18n: {
      field: false, // 属性字段是否国际化转换
      list: false // 数据list是否国际化转换
    },
    multiple: false,

    placeholder: 'piece.oQueryLinkSettingc.buttonicon',
    // 过滤
    filter: {
      // $and: { name: 'xxx', name1: 8, $or: [{ name: 1 }, { name1: 2 }] } // 启用过滤会降低性能
    },
    // 列表字段
    field: ['key'], // 注意与数据对应顺序
    keyField: 'key', // 一行的key值字段
    displayField: 'key',
    // 数据列表
    list: this.getComboboxList()
  };

  created() {
    // this.config = this.value;
    this.G_compID = Tsrv.utils.getGUID();
    /* 如果外部有传入组件信息 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox = new ts.T_compBox(this.G_compID); // 使用本地实例
    } else {
      this.G_compID = this.compBoxInfo.compID;
      this.GT_compBox = this.compBoxInfo.TcompBox;
    }
    this.GT_compBoxInfo = { compID: this.G_compID, TcompBox: this.GT_compBox };
    this.completeParam();
  }

  mounted() {
    /* 向父组件发送实例 */
    this.$emit('compBoxInfo', this.GT_compBoxInfo);
    this.GT_compBox.addCompMergeName(this.G_compID, this.G_compName, this);
  }

  destroyed() {
    /* 注册组件销毁 */
    this.GT_compBox.removeCompMergeName(this.G_compID, this.G_compName);

    /* 如果父组件传入的compBoxInfo则删除本文件产生的引用,反之是本组件产生的ID统一删除 */
    if (Tsrv.utils.isEmpty(this.compBoxInfo)) {
      this.GT_compBox.removeCompsWithCompID(this.G_compID);
    } else {
      this.GT_compBox.removeCompsMergeName(this.G_compID, [
        `'${this.G_compName}'`
      ]);
    }
  }

  private getComboboxList(): Array<any> {
    const l_arr: Array<any> = [];
    for (const key of Tsrv.TiconsFont.getIcons()) {
      l_arr.push({ type: 'iconFont', data: { key } });
    }

    return l_arr;
  }

  private onIconChange(v: any) {
    // 显示图标
    if (this.currChkBtnIdx !== -1) {
      // this.config[this.currChkBtnIdx].icon = v[0].key ? v[0].key : '';
      this.custBtnAttr.m2oIcon = v[0].key ? v[0].key : '';
    }
    this.saveDetailToConfig();
  }

  private saveDetailToConfig(e?: any) {
    const conf = this.config.map(item => {
      return Tsrv.utils.clone(item, true);
    });
    for (const item of conf) {
      delete item.checked;
    }
    if (this.currChkBtnIdx !== -1) {
      if (
        !Tsrv.utils.noValue(this.config) &&
        this.config.length - 1 >= this.currChkBtnIdx
      ) {
        this.config[this.currChkBtnIdx].title = this.custBtnAttr.selTitle;

        this.config[this.currChkBtnIdx].icon = this.custBtnAttr.m2oIcon;

        this.config[this.currChkBtnIdx].action = this.custBtnAttr.m2oSel;
        this.config[
          this.currChkBtnIdx
        ].initDisabled = this.custBtnAttr.initDisabled;
        this.config[
          this.currChkBtnIdx
        ].chkEnabled = this.custBtnAttr.chkEnabled;
        this.config[
          this.currChkBtnIdx
        ].initNotshow = this.custBtnAttr.initNotshow;
        this.config[this.currChkBtnIdx].chkShow = this.custBtnAttr.chkShow;
        this.config[
          this.currChkBtnIdx
        ].singleSelChk = this.custBtnAttr.singleSelChk;
        this.config[
          this.currChkBtnIdx
        ].readCurrentStatus = this.custBtnAttr.readCurrentStatus;
        this.config[
          this.currChkBtnIdx
        ].editedShow = this.custBtnAttr.editedShow;
        this.config[
          this.currChkBtnIdx
        ].editedEnabled = this.custBtnAttr.editedEnabled;
      }
    }
    this.$emit('input', this.config);
    this.$emit('change', this.config);
  }

  /**
   * 增加自定义按钮
   */
  private addCustomBtn() {
    if (this.config) {
      this.config.push({
        checked: false,
        title: 'botton',
        action: '',
        icon: '',
        children: []
      });
    }
    this.saveDetailToConfig();
  }

  /**
   * 移除自定义按钮
   */
  private removeCustomBtn(index?: number) {
    const idx: number = index > -1 ? index : this.currChkBtnIdx;
    if (idx > -1) {
      this.config.splice(idx, 1);
      this.currChkBtnIdx = -1;
      this.saveDetailToConfig();
      this.showAttrSet = false;
    }
  }

  // 自定义按钮被点击
  private customBtnChecked(e: any, item: any, index: number) {
    this.btnCheckedStyle(index);
  }

  private btnCheckedStyle(idx: number) {
    this.currChkBtnIdx = idx;
    this.config.forEach(ele => {
      ele.checked = false;
    });
    this.config[idx].checked = true;
  }

  // 自定义按钮被右点击
  private customBtnRChecked(e: any, item: any, index: number) {
    this.showAttrSet = true;
    this.custBtnAttr = {
      selTitle: item.title,
      m2oIcon: item.icon,
      m2oSel: item.action,
      initDisabled: item?.initDisabled ?? false,
      chkEnabled: item?.chkEnabled ?? false,
      initNotshow: item?.initNotshow ?? false,
      chkShow: item?.chkShow ?? false,
      singleSelChk: item?.singleSelChk ?? false,
      readCurrentStatus: item?.readCurrentStatus ?? false,
      editedShow: item?.editedShow ?? false,
      editedEnabled: item?.readCurrentStatus ?? false
    };

    if (item.children && item.children.length > 0) {
      this.custBtnAttr.selTitle = item.children[0].title;
      this.custBtnAttr.m2oIcon = item.children[0].icon;
      this.custBtnAttr.m2oSel = item.children[0].action;
    }
    this.btnCheckedStyle(index);

    this.$nextTick(() => {
      // 获取自定义按钮的位置信息
      const btnElm = document
        .querySelector(`#custom-btn-${index}`)
        .getBoundingClientRect();
      // 屏幕高度
      const screenH: number =
        document.documentElement.clientHeight || document.body.clientHeight;

      // 窗口尺寸
      const ele = this.$el
        .querySelector('.custom-btn-attrset')
        .getBoundingClientRect();
      this.G_attrSize.left = `-${ele.width + 1}px`;
      // if (e.clientY + ele.height > screenH) {
      //   this.G_attrSize.top = `${e.clientY -
      //     (screenH - e.clientY + ele.height) -
      //     10}px`;
      // } else {
      //   this.G_attrSize.top = `${e.clientY - 58}px`;
      // }
      if (btnElm.top + ele.height > screenH) {
        this.G_attrSize.top = `${btnElm.top - btnElm.height - ele.height}px`;
      } else {
        // this.G_attrSize.top = `${e.clientY - 58}px`;
        this.G_attrSize.top = `${btnElm.top - btnElm.height * 2}px`;
      }

      this.GT_compBox.getCompMergeName(this.G_compID, 'oCombobox')?.initValue(
        this.config[index]?.icon
      );
    });
  }

  private custBtnAttrsetClick() {
    this.showAttrSet = false;
  }

  /**
   * 增加自定义按钮的子按钮
   */
  private addCustomBtnChildren(index: number) {
    this.config[index].children.push({
      title: '',
      action: '',
      children: []
    });
    this.saveDetailToConfig();
  }

  /**
   * 移除自定义按钮的子按钮
   */
  private removeCustomBtnChildren(index: number, subIndex: number) {
    this.config[index].children.splice(subIndex, 1);
    this.saveDetailToConfig();
  }

  private completeParam() {
    Array.isArray(this.config) &&
      this.config.forEach(item => {
        Object.prototype.hasOwnProperty.call(item, 'isShow') &&
          (item['isShow'] = true);
      });
  }
}
</script>

<style scoped lang="scss">
.cusbtn {
  .table-title {
    // margin-top: 10px;
    height: 30px;
    line-height: 30px;
    .ivu-icon {
      float: left;
      margin-top: 5px;
      font-size: 18px;
    }
  }
  .custom-btn-content {
    display: grid;
    // grid-template-columns: repeat(auto-fill, 150px);
    grid-template-columns: 1fr 1fr;
    grid-gap: 5px 5px;
    .custom-btn-container {
      padding: 2px;
      text-align: center;
      overflow: hidden;
    }
    .checked {
      border: solid 1px #2d8eff;
    }
  }

  // .title {
  //   display: block;
  //   line-height: 45px;
  //   font-weight: bold;
  // }
  .custom-btn-add {
    // font-size: 18px;
    // color: #666;
    // position: absolute;
    // right: 0;
    // top: 14px;
    cursor: pointer;
  }
  .custom-btn-remove {
    cursor: pointer;
    margin-left: 6px;
  }
  .custom-btn-cell {
    .custom-btn-primary,
    .custom-btn-child {
      margin-bottom: 10px;
      display: flex;
      .custom-btn-title {
        width: 75px;
        margin-right: 10px;
        flex-shrink: 0;
      }
      .custom-btn-icon {
        width: 75px;
        margin-right: 10px;
        flex-shrink: 0;
      }
      .custom-btn-action {
        margin-right: 10px;
      }
      .ivu-icon {
        font-size: 18px;
        line-height: 32px;
        margin: 0 0 0 5px;
        cursor: pointer;
      }
    }
    .custom-btn-child > span {
      line-height: 32px;
      padding: 0 10px;
    }
  }
}

.custom-btn-checkbox-left {
  .ivu-col {
    text-align: left;
  }
}
.custom-btn-attrset {
  border: 1px solid #ddd;
  padding: 6px 10px 6px 10px;
  position: absolute;
  top: 0px;
  left: 0px;
  width: 300px;
  z-index: 10;
  background: #fff;
  display: grid;
  grid-row-gap: 6px;
  text-align: center;
  box-shadow: 4px 4px 15px #ddd;
}
</style>
